package com.qf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * 决绝全局乱码的过滤器
 * @WebFilter里面的fileName属性--->等价于xml配置里面<filter-name></filter-name>
 *              initParams属性---->等于xml里面的<init-param> 初始化参数
 *              urlPattarns和value属性---等价于<url-pattern> ,仅仅给出一个属性参数,value和urlPatterns省略不写
 */
@WebFilter("/*")
public class CharacterFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws ServletException, IOException {
      //  System.out.println("doFilter执行了");
        //解决全局乱码
        //获取具体的请求对象httpServletRequest以及具体的响应对象HttpServletresponse
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取前台提交方式
        String method = request.getMethod();
        //如果是"POST",解决POST乱码
        if("POST".equals(method)){
            request.setCharacterEncoding("utf-8") ;
        }
        //如果有响应的乱码
        response.setContentType("text/html;charset=utf-8")  ;

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        System.out.println("全局过滤器初始化了");
    }

    public void destroy() {
        System.out.println("全局过滤器销毁了");
    }


}
